package util

import (
	"bufio"
	"context"
	"fmt"
	"os/exec"
	"syscall"
	"time"
)

var (
	// Timeout cmd执行超时的秒数
	Timeout = 30 * time.Second
)

func CommandTimeOut(call func(bytes []byte, err error), name string, arg ...string) {
	ctxt, cancel := context.WithTimeout(context.Background(), Timeout)
	defer cancel()
	// 通过上下文执行，设置超时
	cmd := exec.CommandContext(ctxt, name, arg...)
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	stdout0, err := cmd.StdoutPipe() // 获取命令输出内容
	if err != nil {
		call(nil, err)
		return
	}
	if err := cmd.Start(); err != nil {
		call(nil, err)
		return
	}
	scanner := bufio.NewScanner(stdout0)
	for scanner.Scan() {
		call(scanner.Bytes(), nil)
	}
	if err := scanner.Err(); err != nil {
		call(scanner.Bytes(), err)
	}
}

func Command(name string, arg ...string) {
	cmd := exec.Command(name, arg...)
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	err := cmd.Start()
	if err != nil {
		fmt.Println(err)
	}
}
